//get_post_comments_by_link
//get_post_detail_by_link
const getPost = {
    getData: {},
    postList: {
        collect_id: '',
        post: []
    },
    taskConfig: { taskStatus: false },
    viewCommentList: [],
    CommentList: [],
    tipContent: { get_post_comments_by_link: '链接采集评论用户', get_post_detail_by_link: '链接采集笔记内容' },
    watchValue(key, newVal) {
        if (key == 'taskStatus' && newVal) {
            //当前回复任务已全部完成
            if (getPost.postList.post.length) {
                getPost.postList.post[0].comments = getPost.CommentList
            }
            console.log('爬笔记任务完成' + JSON.stringify(getPost.postList));
            console.log('收集的评论' + JSON.stringify(getPost.CommentList));

            if (!getPost.taskConfig.errorTask) {
                back()
                sleep(1000)
                back()
            }
            Xhs.taskConfig.taskStatus = true
        }
        if (key == 'errorTask' && newVal) {
            let skey = getPost.getData.skey
            // 所有任务数据均执行异常
            let params = {
                taskType: skey,
                task_id: getPost.getData.task_id,
                taskName: getPost.tipContent[skey],
                taskData: getPost.getData,
                errorTip: newVal,
                taskDate: Comman.getDate()
            }
            Xhs.errorTask(params)
            getPost.taskConfig.taskStatus = true
        }
    },
    init(data) {
        getPost.getData = data;
        getPost.viewCommentList = []
        getPost.CommentList = []
        getPost.postList = {
            collect_id: data.setting.collect_id || '',
            post: []
        }
        getPost.taskConfig = Comman.defineReactive(
            {
                taskStatus: false,
                errorTask: ''
            },
            '',
            getPost.watchValue
        )
        getPost.openTask()
    },
    start(data) {
        //初始化数据
        // console.log('开始发帖,数据：',data);
        getPost.init(data)
    },
    openTask() {
        let homeMnue = btnConfig.home.homeMnue
        //重置首页
        while (!depth(homeMnue.options.depth).id(homeMnue.options.id).exists()) {
            back();
            console.log('back...');
            sleep(2000);
        }
        getPost.toVIew()

    },
    toVIew() {
        let like = getPost.getData.setting.collect_content
        if (!like) {
            //没有帖子id 直接返回
            getPost.taskConfig.taskStatus = true
            return
        }
        setClip('')
        home()
        setClip(like)
        sleep(1000)
        Xhs.openApp()
        App.randomSleep(2, 5)

        let viewBtn = btnConfig.post.viewBtn.default()
        if (viewBtn) {
            if (viewBtn.bounds) {
                App.clickByBtn(viewBtn, true)
            } else {
                App.click(btnConfig.post.viewBtn.position.x, btnConfig.post.viewBtn.position.y, true)
            }
            let textTip = text('当前内容无法展示').findOne(1000) || text('视频暂不可查看').findOne(1000)
            if (textTip) {
                console.log('链接无法查看，任务返回失败状态');
                getPost.taskConfig.errorTask = '链接无法查看'
            }
            let infoDom = btnConfig.post.contentInfo.default()
            let infoDom2 = btnConfig.post.contentInfo2.default()
            let titleDom = btnConfig.post.titleInfo.default()
            let likeDom = className('android.widget.Button').descContains('点赞').findOne(2000)
            let saveDom = className('android.widget.Button').descContains('收藏').findOne(2000)
            let commentDom = className('android.widget.Button').descContains('评论').findOne(2000)
            let shareBrn = btnConfig.post.shareBrn.default()
            if (commentDom) {
                let postInfo = {
                    link: "",
                    title: titleDom ? titleDom.text() : '',
                    content: infoDom ? infoDom.text() : infoDom2 ? infoDom2.desc() : '',
                    like_num: likeDom ? likeDom.desc().split('点赞')[1] * 1 : 0,
                    save_num: saveDom ? saveDom.desc().split('收藏')[1] * 1 : 0,
                    comment_num: commentDom ? commentDom.desc().split('评论')[1] * 1 : 0,
                    send_time: '',
                    comments: []
                }
                // getPost.getLinke(shareBrn, postInfo)
                postInfo['link'] = like
                getPost.postList.post.push(postInfo)
                if (getPost.getData.skey == 'get_post_comments_by_link') {
                    getPost.resolveCommant()//链接采集笔记评论用户
                } else {
                    //链接采集笔记内容 - 已完成
                    getPost.taskConfig.taskStatus = true
                }
            } else {
                console.log('找不到评论按钮');
                getPost.taskConfig.errorTask = '找不到评论按钮'
            }
        } else {
            // 查询不到
            getPost.taskConfig.errorTask = '剪贴板/帖子弹出出错，无法识别查看按钮'
        }
    },
    resolveCommant() {
        let resolveBtn = btnConfig.post.resolveBtn.default()
        if (!resolveBtn) {
            console.log('找不到评论按钮-无法调出评论列表');
            getPost.taskConfig.errorTask = '找不到评论按钮-无法调出评论列表'
        }
        if (resolveBtn.bounds) {
            App.clickByBtn(resolveBtn, 3)
        } else {
            App.click(btnConfig.post.resolveBtn.position.x, btnConfig.post.resolveBtn.position.y, 3)
        }
        let page = 1
        getPost.resolveCommantList(page)
    },
    resolveCommantList(page) {
        if (page >= Xhs.CommentPage) {
            if (!getPost.taskConfig.taskStatus) {
                getPost.taskConfig.taskStatus = true
            }
            console.log('评论页数超过设定值，停止收集')
            return
        }
        let setting = getPost.getData.setting
        let maxNum = setting.num || 0
        console.log('开始解析评论列表', maxNum, getPost.CommentList.length);

        if (getPost.CommentList.length >= maxNum) {
            console.log('已达到最大评论数，停止解析');
            if (!getPost.taskConfig.taskStatus) {
                getPost.taskConfig.taskStatus = true
            }
            return
        }
        let commentList = btnConfig.post.commentList.default() || btnConfig.post.commentList2.default()
        if (!commentList) {
            getPost.CommentList = []
            console.log('找不到评论列表');
            // getPost.taskConfig.errorTask = true
            return
        }
        let commentItems = btnConfig.post.commentItem1.default()
        if (!commentItems.length) {
            console.log('没有评论内容');
            //直接完成任务
            if (!getPost.taskConfig.taskStatus) {
                getPost.taskConfig.taskStatus = true
            }
            return
        } else {
            console.log('评论列表：', commentItems.length + '\n关键词：' + setting.collect_keyword);
        }
        commentItems.forEach((commentItem) => {
            if (getPost.CommentList.length >= maxNum) {
                console.log('已达到最大评论数，停止解析');
                if (!getPost.taskConfig.taskStatus) {
                    getPost.taskConfig.taskStatus = true
                }
                return
            }
            let text = commentItem.findOne(id('jch'))
            let name = commentItem.findOne(id('jjo'))
            if (!text || !name) {
                return
            }
            console.log('当前浏览评论用户: ' + name.text() + ' 内容: ' + text.text());
            //查询是否浏览过
            let findIndex = getPost.viewCommentList.findIndex((item) => {
                return item == name.text()
            })
            //未浏览过的用户评论，收集
            if (findIndex == -1 && setting.collect_keyword.some((item)=>text.text().includes(item))) {
                getPost.viewCommentList.push(name.text())
                getPost.filterCommant(text.text(), commentItem)
            }
            sleep(1000)
        });
        console.log('scrollForward()', commentList.scrollable());

        if (commentList.scrollable()) {
            //可以滑动
            if (commentList.scrollForward()) {
                getPost.resolveCommantList((page += 1))
            } else {
                console.log('滑动失败，没有更多评论了');
                if (!getPost.taskConfig.taskStatus) {
                    getPost.taskConfig.taskStatus = true
                }
            }
        } else {
            console.log('没有更多评论了');
            if (!getPost.taskConfig.taskStatus) {
                getPost.taskConfig.taskStatus = true
            }
            //触底了
        }
    },
    filterCommant(commanText, commentItem) {
        console.log('filterCommant');

        if (commanText.includes('-') || commanText.includes('6天前')) {
            //超时，不涉及
            return
        }
        let imgBtn = commentItem.findOne(id('e98'))
        if (!imgBtn) {
            console.log('找不到图片按钮');
            return
        }
        App.clickByBtn(imgBtn, 3)
        let userNick = btnConfig.user.userPageNick.default()
        let userLocation = btnConfig.user.userPageLocation.default()
        let userId = btnConfig.user.userPageId.default()

        if (userId) {
            let commentInfo = {
                content: commanText,
                xhsid: userId ? userId.text().replace('小红书号：', '') : '',
                nickname: userNick ? userNick.text() : '',
                avatar: "",
                ip: userLocation ? userLocation.text().replace('IP属地：', '') : '',
            }
            console.log('comments', commentInfo);
            getPost.CommentList.push(commentInfo)
        }
        back()
        sleep(2000)
    },
    getLinke(shareBrn, postInfo) {
        if (shareBrn) {
            App.clickByBtn(shareBrn, 3)
            let moreBtnMenu = btnConfig.post.moreBtnMenu.default()
            let copyBtn = btnConfig.post.copyBtn.default()
            if (!moreBtnMenu) {
                console.log('找不到moreBtnMenu');
            }
            if (!copyBtn) {
                let scroll = true
                while (!copyBtn && scroll) {
                    try {
                        scroll = moreBtnMenu.scrollForward()
                        sleep(2000)
                        copyBtn = btnConfig.post.copyBtn.default()
                        sleep(2000)
                    } catch (error) {
                        scroll = false
                    }
                }
                if (!copyBtn) {
                    console.log('找不到复制链接按钮');
                }
            }
            if (copyBtn.bounds) {
                App.clickByBtn(copyBtn, true)
            } else {
                App.click(btnConfig.post.copyBtn.position.x, btnConfig.post.copyBtn.position.y, true)
            }
            // launch(Xhs.AppPackName)
            // sleep(1000)
            // postInfo['link'] = getClip() || ''
            // sleep(3000)
            // launch(Xhs.packName);
            let resolveInputBtn = btnConfig.post.resolveInputBtn.default()
            if (resolveInputBtn) {
                App.clickByBtn(resolveInputBtn, 3)
                let input = btnConfig.post.resolveInput.default() || btnConfig.post.resolveInput2.default()
                if (input) {
                    input.paste()
                    App.randomSleep(2, 4)
                    input = btnConfig.post.resolveInput.default() || btnConfig.post.resolveInput2.default()
                    postInfo['link'] = input ? input.text() : '查询文章链接失败'
                    setText('')
                    sleep(1000)
                    back()
                }
                sleep(2000)
            } else {
                console.log('找不到输入框');
            }
        } else {
            console.log('找不到分享按钮');
        }
    },
}
module.exports = getPost